package com.lingnan.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingnan.common.utils.ResultEntity;
import com.lingnan.eduservice.clientinterface.VodClient;
import com.lingnan.eduservice.entity.po.EduVideoPO;
import com.lingnan.eduservice.mapper.EduVideoMapper;
import com.lingnan.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.servicebase.excetioncontrooller.LingNanException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author zzd
 * @since 2021-08-17
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideoPO> implements EduVideoService {

    @Autowired
    private VodClient vodClient;
    /**
     * 根据小节ID删除小节功能
     * @param videoId
     */
    @Override
    public void deleteVideoById(String videoId) {
        // 通过视频ID查询课程信息
        EduVideoPO eduVideoPO = baseMapper.selectById(videoId);
        // 获取云端视频ID
        String videoSourceId = eduVideoPO.getVideoSourceId();
        // 判断是否有上传视频到云端
        if(!(StringUtils.isEmpty(videoSourceId) || videoId.length() <= 0)){
            // 如果存在则调用远程服务删除
            ResultEntity resultEntity = vodClient.deleteVideoByVideoSourceId(videoSourceId);
            // 开启熔断机制
            if(resultEntity.getCode() == 20001){
                throw new LingNanException(20001,"删除视频超时");
            }
        }
        // 删除小节信息
        baseMapper.deleteById(videoId);
    }

    /**
     * 根据课程ID删除课程所有小节、视频信息
     * @param courseId
     */
    @Override
    public void deleteVideoByCourseId(String courseId) {
        // 删除所有云端上的视频

        // 查询所有云端上的视频
        QueryWrapper<EduVideoPO> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        videoWrapper.select("video_source_id");
        List<EduVideoPO> eduVideoPOList = baseMapper.selectList(videoWrapper);
        // 创建存储所有视频ID的容器
        List<String> videoSourceIdList = new ArrayList<>(100);

        // 将数据转换格式
        for (EduVideoPO eduVideoPO : eduVideoPOList) {

            String videoSourceId = eduVideoPO.getVideoSourceId();
            // 查询是否存在视频ID
            if(!(StringUtils.isEmpty(videoSourceId) || videoSourceId.length()<=0)){
                // 存在视频ID
                videoSourceIdList.add(videoSourceId);
            }
        }
        // 判断是否存在课程信息
        if(!(videoSourceIdList.size() <= 0 || null == videoSourceIdList)){
            // 调用远程接口批量删除课程视频信息
            vodClient.deleteAllVideo(videoSourceIdList);
        }

        // 删除当前课程所有小节信息

        // 创建查询条件
        QueryWrapper<EduVideoPO> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        // 执行删除
        baseMapper.delete(wrapper);


    }
}
